package io;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: zhenzhong.wang
 * @Time: 2018/4/20 11:42
 */
public class NIODemo {

  /**
   * FileChannel读取文件并打印
   *
   * @throws IOException
   */
  @Test
  public void testOne() throws IOException {
//    RandomAccessFile afile = new RandomAccessFile("C:\\Users\\ZZWang\\Desktop\\DMP4SaasWebApplication.json", "rw");
    FileInputStream afile = new FileInputStream("C:\\Users\\ZZWang\\Desktop\\DMP4SaasWebApplication.json");
    FileChannel channel = afile.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(30);

    while (channel.read(buffer) != -1) {
      buffer.flip();
      while (buffer.hasRemaining()) {
        System.out.print((char) buffer.get());
      }

//      buffer.rewind();
//      System.out.println("\n\n测试\n\n");
//      while (buffer.hasRemaining()) {
//        System.out.print((char) buffer.get());
//      }
      buffer.clear();
    }
    afile.close();
  }

  /**
   * scatter和gather的使用
   *
   * @throws IOException
   */
  @Test
  public void testTwo() throws IOException {
    FileInputStream afile = new FileInputStream("C:\\Users\\ZZWang\\Desktop\\DMP4SaasWebApplication.json");
    FileChannel channel = afile.getChannel();

    // 创建ByteBuffer数组
    ByteBuffer head = ByteBuffer.allocate(20);
    ByteBuffer body = ByteBuffer.allocate(60);
    ByteBuffer[] buf = {head, body};

    // 读取channel数据到buffer数组，scatter
    while (channel.read(buf) != -1) {
      head.flip();
      body.flip();
       /* while (head.hasRemaining()) {
        System.out.print((char) head.get());
      }*/
      while (body.hasRemaining()) {
        System.out.print((char) body.get());
      }
      head.clear();
      body.clear();
    }
    afile.close();
  }

  @Test
  public void testThree() throws IOException {
    FileChannel fromChannel = new FileInputStream("C:\\Users\\ZZWang\\Desktop\\DMP4SaasWebApplication.json").getChannel();
    FileChannel toChannel = new FileInputStream("C:\\Users\\ZZWang\\Desktop\\test.json").getChannel();

    long size = fromChannel.size();
    toChannel.transferFrom(fromChannel, 0, size);

  }

}
